package com.damn;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;



import com.damn.RestFB;
import com.damn.URLResponse;
import com.damn.bean.GeneralBean;
import com.damn.bean.FileScheduleBean;
import com.oreilly.servlet.MultipartRequest; 
/**
 * Servlet implementation class FBAutoServlet
 */
public class FBAutoServlet extends HttpServlet {
	private static final String redirectURL = "http://free.hostingjava.it/-javaspace/FBAuto?action=";
	
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FBAutoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String action = request.getParameter("action");		
		System.out.println("Action ="+ action);
		FBService fbServ = new FBService();
		String responseStr = "";
		
		if(action!=null && !action.equals(""))		{
			
			if(action.equalsIgnoreCase("newUser"))	{
				String uName = request.getParameter("username");
				String Pwd = request.getParameter("password");
				System.out.println(uName);
				System.out.println(Pwd);
				if(uName != null && Pwd != null && !uName.equals("") && !Pwd.equals(""))	{
					
					responseStr = fbServ.storeUser(uName, Pwd);
					System.out.println(responseStr);
					if(responseStr.equalsIgnoreCase("success"))	{
						System.out.println("User Name stored in session :" + uName);
						request.getSession().setAttribute("uName", uName);
						String customAction = "FBRdrt"+uName;
						String FBUrl = "https://www.facebook.com/dialog/oauth?client_id=348522271861961&redirect_uri="+redirectURL+customAction+"&scope=publish_stream,manage_pages,read_stream,user_about_me,user_activities,user_birthday,user_checkins,user_education_history,user_events,user_likes,user_location,user_photos,user_relationships,user_status,user_videos,email";
						System.out.println(FBUrl);
						response.sendRedirect(FBUrl);
					}else if(responseStr.equalsIgnoreCase("userExist"))	{
						request.setAttribute("msgStr", "User Already Exists");
						//request.getSession().removeAttribute("uName");
						request.getRequestDispatcher("login.jsp").forward(request, response);
					}else	{
						request.setAttribute("msgStr", "An Error occured. Level 1");
						//request.getSession().removeAttribute("uName");
						request.getRequestDispatcher("login.jsp").forward(request, response);						
					}
				}else	{
					request.setAttribute("msgStr", "An Error occured. Level 2");
					//request.getSession().removeAttribute("uName");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				}		
				
			}
			
			else if(action.indexOf("FBRdrt") != -1)	{
				
				String redirectCode = request.getParameter("code");
				String uName = action.substring(action.indexOf("FBRdrt")+6, action.length());				
				System.out.println("User Name = "+uName);
				System.out.println(redirectCode);
				if(redirectCode!=null && uName!=null && !redirectCode.equals("") && !uName.equals(""))	{
					
					System.out.println(redirectCode);										
					responseStr = fbServ.storeCode(redirectCode,uName);					
					if(responseStr.equals("success"))	{
						System.out.println("done");
						URLResponse urlRes = new URLResponse();
						String customAction = "FBRdrt"+uName;
						String FBUrl = "https://graph.facebook.com/oauth/access_token?client_id=348522271861961&redirect_uri="+redirectURL+customAction+"&response_type=token&client_secret=4c467505178afb83648674e5727c60e3&code="+redirectCode; 
						StringBuffer token = urlRes.getURLResponse(FBUrl);						
						String tokenStr = token.toString();
						System.out.println("Token B = "+tokenStr);
						tokenStr = tokenStr.substring(0, tokenStr.indexOf("&expires="));
						tokenStr = tokenStr.replaceAll("access_token=","");
						System.out.println("Token A = "+tokenStr);
						
						responseStr = fbServ.storeToken(tokenStr,uName);
						if(responseStr.equalsIgnoreCase("success"))	{
							
							responseStr = fbServ.storeOthers(fbServ.getOtherAccess(tokenStr), uName);
							System.out.println(responseStr);
							if(responseStr.equalsIgnoreCase("success"))	{
								request.setAttribute("msgStr", "Registration Successful<br/>Login To Continue");
								request.getRequestDispatcher("login.jsp").forward(request, response);
							}else	{
								request.setAttribute("msgStr", "An Error occured. Level 9");								
								request.getRequestDispatcher("login.jsp").forward(request, response);
							}							
						}else	{
							request.setAttribute("msgStr", "An Error occured. Level 3");
							//request.getSession().removeAttribute("uName");
							request.getRequestDispatcher("login.jsp").forward(request, response);
						}											
					}else	{
						request.setAttribute("msgStr", "An Error occured. Level 4");
						//request.getSession().removeAttribute("uName");
						request.getRequestDispatcher("login.jsp").forward(request, response);
					}					
				}else	{
					request.setAttribute("msgStr", "An Error occured. Level 5");
					//request.getSession().removeAttribute("uName");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				} 
			}
			
			else if(action.equalsIgnoreCase("login")){
				String uName = request.getParameter("username");
				String Pwd = request.getParameter("password");
				ArrayList<GeneralBean> listOfAccess = fbServ.checkLogin(uName, Pwd);				
				if(listOfAccess.size()>0)	{
					request.getSession().setAttribute("uName", uName);
					request.getSession().setAttribute("Pwd", Pwd);
					request.getSession().setAttribute("listOfAccess", listOfAccess);
					request.getRequestDispatcher("main.jsp").forward(request, response);
				}else	{
					request.setAttribute("msgStr", "Invalid Username / Password");
					//request.getSession().removeAttribute("uName");
					request.getRequestDispatcher("login.jsp").forward(request, response);
				}				
			}
			
			else if(action.equalsIgnoreCase("logout")){				
				request.getSession().removeAttribute("uName");
				request.getSession().removeAttribute("Pwd");
				request.getSession().removeAttribute("listOfAccess");				
				request.getRequestDispatcher("login.jsp").forward(request, response);					
			}
			
			else if(action.equalsIgnoreCase("FBPostMsg"))	{
				MultipartRequest multi = new MultipartRequest(request,"/home/hostingjava.it/javaspace/docs");			
				String uName = (String)request.getSession().getAttribute("uName");
				String Pwd = (String)request.getSession().getAttribute("Pwd");
				
				String FBMessage = multi.getParameter("FBMessage");
				ArrayList<String> indexArray = fbServ.getAccessIndexArray(multi);
				ArrayList<String> tokenArray = fbServ.getToken(uName, Pwd,indexArray);				
				System.out.println(uName+" "+Pwd+" "+FBMessage+" "+tokenArray.size());
				
				if(tokenArray.size()>0 && FBMessage!=null)	{
					for(int index = 0;index<tokenArray.size();index++)	{
						RestFB fbClient= new RestFB();
						responseStr = fbClient.initFBClient(tokenArray.get(index));
						if(responseStr.equalsIgnoreCase("success"))	{
							responseStr = fbClient.CreatePost(FBMessage);
							if(!responseStr.equalsIgnoreCase("success"))	{
								responseStr = "done";
								request.setAttribute("msgStr", "Unable to Post Message");							
								request.getRequestDispatcher("main.jsp").forward(request, response);
							}
						}else	{
							responseStr = "done";
							request.setAttribute("msgStr", "Unable to Post Message");							
							request.getRequestDispatcher("main.jsp").forward(request, response);
						}
					}
					if(!responseStr.equalsIgnoreCase("done"))	{					
						request.setAttribute("msgStr", "Message Posted Successfuly");							
						request.getRequestDispatcher("main.jsp").forward(request, response);
					}
				}else	{
					request.setAttribute("msgStr","Unable to Post Message");							
					request.getRequestDispatcher("main.jsp").forward(request, response);
				}
			}		
			
			else if(action.equalsIgnoreCase("uploadPic"))	{
				
				MultipartRequest multi = new MultipartRequest(request,"/home/hostingjava.it/javaspace/docs",Integer.MAX_VALUE);				
				String caption = multi.getParameter("caption");
				System.out.println("Caption = "+caption);							
				Enumeration filesEn = multi.getFileNames();
				
				String tempName = "";
				String fileName = "";
				
				while (filesEn.hasMoreElements())
	            {
					tempName = (String)filesEn.nextElement();
	                fileName = multi.getFilesystemName(tempName);
	                System.out.println(fileName);
	            }				
				File uploadedFile = multi.getFile("fileIp");				
								
				
				String uName = (String)request.getSession().getAttribute("uName");
				String Pwd = (String)request.getSession().getAttribute("Pwd");
							
				ArrayList<String> indexArray = fbServ.getAccessIndexArray(multi);
				ArrayList<String> tokenArray = fbServ.getToken(uName, Pwd,indexArray);
				System.out.println(uName+" "+Pwd+" "+caption+" "+tokenArray.size());
				if(tokenArray.size()>0 && caption!=null)	{
					for(int index = 0;index<tokenArray.size();index++)	{
						RestFB fbClient= new RestFB();
						responseStr = fbClient.initFBClient(tokenArray.get(index));
						if(responseStr.equalsIgnoreCase("success"))	{
							InputStream picStream = new BufferedInputStream(new FileInputStream(uploadedFile));
							responseStr = fbClient.publishPhoto(picStream, caption);
							responseStr = "success";
							if(!responseStr.equalsIgnoreCase("success"))	{
								request.setAttribute("msgStr", "Unable to Post Message");							
								request.getRequestDispatcher("main.jsp").forward(request, response);
							}
						} else {
							request.setAttribute("msgStr", "Unable to Post Message");							
							request.getRequestDispatcher("main.jsp").forward(request, response);
						}
					}
					request.setAttribute("msgStr", "Photo Posted Successfuly");							
					request.getRequestDispatcher("main.jsp").forward(request, response);					
				}else	{
					request.setAttribute("msgStr","Unable to Post Message");							
					request.getRequestDispatcher("main.jsp").forward(request, response);
				}			
			}			
			
			
			else if(action.equalsIgnoreCase("schedulePic"))	{
				
				MultipartRequest multi = new MultipartRequest(request,"/home/hostingjava.it/javaspace/docs",Integer.MAX_VALUE);				
				String caption = multi.getParameter("caption");
				System.out.println("Caption = "+caption);							
				/*
				Enumeration filesEn = multi.getFileNames();			
				
				String tempName = "";
				String fileName = "";
				
				while (filesEn.hasMoreElements())
	            {
					tempName = (String)filesEn.nextElement();
	                fileName = multi.getFilesystemName(tempName);
	                System.out.println(fileName);
	            }
	            */
				File uploadedFile = null;
				Calendar calendar = new GregorianCalendar();							
								
				ArrayList<FileScheduleBean> fileScheduleAr = new ArrayList<FileScheduleBean>();
				/*
				if(fileIndexArray!=null)		{
				for(int index = 0;index<fileIndexArray.length;index++)	{							
					if(fileIndexArray[index].equals("1"))
					{
					*/
					ArrayList<FileScheduleBean> fileSchAr = new ArrayList<FileScheduleBean>();	
					for(int index = 0;index<=9;index++)
					{
					uploadedFile = multi.getFile("fileIp"+index);
					if(uploadedFile!=null)
					{
					FileScheduleBean fileSchBean = new FileScheduleBean();
					fileSchBean.setFileName(uploadedFile.getName());
					File tempRenameFile = new File("/home/hostingjava.it/javaspace/docs/"+
											calendar.get(Calendar.YEAR)+calendar.get(Calendar.MONTH)+calendar.get(Calendar.DATE)+
											calendar.get(Calendar.HOUR)+calendar.get(Calendar.MINUTE)+calendar.get(Calendar.SECOND)+index);
					uploadedFile.renameTo(tempRenameFile);
					
					System.out.println(tempRenameFile.getPath());
					System.out.println(fbServ.getParaFromReq(multi, "hr"+index));
					System.out.println(fbServ.getParaFromReq(multi, "min"+index));
					System.out.println(fbServ.getParaFromReq(multi, "caption"+index));
					
					fileSchBean.setFilePath(tempRenameFile.getPath());
					fileSchBean.setSchHour(fbServ.getParaFromReq(multi, "hr"+index));
					fileSchBean.setSchMin(fbServ.getParaFromReq(multi, "min"+index));
					fileSchBean.setCaption(fbServ.getParaFromReq(multi, "caption"+index));
					fileSchAr.add(fileSchBean);
					}					
					}
					if(fileSchAr != null && fileSchAr.size() > 0)	{				
						String uName = (String)request.getSession().getAttribute("uName");
						ArrayList<String> profileIndexAr = fbServ.getAccessIndexArray(multi);
						responseStr = fbServ.storeScheduleArray(fileSchAr, uName, profileIndexAr);
						if(responseStr.equals("success"))	{
							request.setAttribute("msgStr", "Post scheduled successfully");							
							request.getRequestDispatcher("main.jsp").forward(request, response);
						}
						else	{
							request.setAttribute("msgStr", "An error storing the data. Please try again");							
							request.getRequestDispatcher("main.jsp").forward(request, response);
						}
					}
					else	{
						request.setAttribute("msgStr", "An error occured while scheduling the post.");							
						request.getRequestDispatcher("main.jsp").forward(request, response);
					}
						
						
					
			/*		
			}
					//fileArray.add(tempRenameFile.getAbsolutePath());
				}
				*/
				//Cleanup.......				
				//Cleanup Ends.....
				/*
				InputStream picStream = new BufferedInputStream(new FileInputStream(uploadedFile));				
				
				String uName = (String)request.getSession().getAttribute("uName");
				String Pwd = (String)request.getSession().getAttribute("Pwd");
							
				ArrayList<String> indexArray = fbServ.getAccessIndexArray(multi);
				ArrayList<String> tokenArray = fbServ.getToken(uName, Pwd,indexArray);
				System.out.println(uName+" "+Pwd+" "+caption+" "+tokenArray.size());
				if(tokenArray.size()>0 && caption!=null)	{
					for(int index = 0;index<tokenArray.size();index++)	{
						RestFB fbClient= new RestFB();
						responseStr = fbClient.initFBClient(tokenArray.get(index));
						if(responseStr.equalsIgnoreCase("success"))	{
							responseStr = fbClient.publishPhoto(picStream, caption);
							responseStr = "success";
							if(!responseStr.equalsIgnoreCase("success"))	{
								request.setAttribute("msgStr", "Unable to Post Message");							
								request.getRequestDispatcher("main.jsp").forward(request, response);
							}
						} else {
							request.setAttribute("msgStr", "Unable to Post Message");							
							request.getRequestDispatcher("main.jsp").forward(request, response);
						}
					}
					request.setAttribute("msgStr", "Photo Posted Successfuly");							
					request.getRequestDispatcher("main.jsp").forward(request, response);					
				}else	{
					request.setAttribute("msgStr","Unable to Post Message");							
					request.getRequestDispatcher("main.jsp").forward(request, response);
				}
				*/
				//}
			}	
			
			else	{
				request.setAttribute("msgStr", "An Error occured. Level 6");
				//request.getSession().removeAttribute("uName");
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
		}
		
		else	{		
			request.setAttribute("msgStr", "An Error occured. Level 7");
			//request.getSession().removeAttribute("uName");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}		
	}	
}
